﻿using System;
using System.Linq;
using Dapper;
using ErrCode.Model;

namespace ErrCode.Dal
{
    public class MessageCodeDal : BaseDal
    {
        public MethodCode GetMethodCodeByMethodName(string methodName, int projectId)
        {
            string sql = "SELECT * FROM methodCode where methodname =@methodName and  SystemId=@projectId";

            var result = ErrCodeSysConnection.Query<MethodCode>(sql, new { methodName, projectId });

            if (result == null)
            {
                return null;
            }
            int count = result.Count();
            if (count > 1)
            {
                throw new Exception("Method重名");
            }
            if (count == 0)
            {
                return null;
            }
            return result.ToList()[0];
        }

        public int InsertMethodCode(MethodCode methodCode)
        {
            string sql = "INSERT INTO `MethodCode` ( `MethodName`, `Seed`,`SystemId`,`SystemMethodId`) VALUES ( @MethodName, @Seed,@SystemId,@SystemMethodId);SELECT LAST_INSERT_ID();";
            return ErrCodeSysConnection.ExecuteScalar<int>(sql, methodCode);
        }
        public int InsertMethodResultCode(MethodResultCode resultCode)
        {
            string sql = "INSERT INTO `MethodResultCode` ( `MethodId`, `Message`, `Code`) VALUES (@MethodId, @Message, @Code);SELECT LAST_INSERT_ID();";
            return ErrCodeSysConnection.ExecuteScalar<int>(sql, resultCode);
        }

        public int UpdateMethodCodeSeed(MethodCode methodCode)
        {
            string sql = "UPDATE `MethodCode` SET `Seed`=@Seed WHERE (`Id`=@Id);";
            return ErrCodeSysConnection.Execute(sql, methodCode);
        }

        public MethodCode GetMethodCodeByMethodId(int systemMethodId, int systemId)
        {
            string sql = "select * from methodCode where SystemId = @systemId and SystemMethodId=@systemMethodId";
            return ErrCodeSysConnection.Query<MethodCode>(sql, new { systemMethodId,systemId }).SingleOrDefault();
        }
    }

}
